import md5
import urllib
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import images

from Img import Img
import utils.imageutils as imageutils
from Img import NotSupportedImageEncodingError

import logging

class stealimg(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        if not user:
            self.redirect(users.create_login_url(urllib.unquote_plus(self.request.uri)))
            return
        #request.path_qs      #/steal/http%3A//www.sgei.com%252Ffjalg.asp%253Ffjao%253Dtwr?ffff=7
        imgurl = self.request.path_qs[len('/steal/'):]
        imgurl = urllib.unquote_plus(imgurl)
        #self.response.out.write(self.request.url)
        #self.response.out.write(imgurl)
        #return
        heads = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)',
                 'referer' : webapp.Request.blank(imgurl).host_url}
        #self.response.out.write(imgurl)
        #self.response.out.flush()
        resp = urlfetch.fetch(imgurl,
               method=urlfetch.GET,
               headers=heads)
        #self.response.out.write('\n--------------------------------\n')
        #self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))
        #self.response.out.write('\n--------------------------------\n')
        #self.response.out.write(resp.content)

        #self.response.headers['content-type'] = resp.headers['content-type']
        #self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))

        if resp.status_code == 200:
            content_type = resp.headers.get('Content-Type')
            if content_type and content_type.split('/')[0].lower() == 'image':
                imgEncoding = content_type.split('/')[1].upper()
                if Img.isSupported(imgEncoding):
                    #is image, we compute md5sum
                    imgId = md5.new(resp.content).hexdigest()
                    if len(Img.all().filter('imgId = ',imgId).fetch(1)) == 0:
                        #not exists
                        #get thumbnail first
                        try:
                            tb = imageutils.thumbnailimage(resp.content)[0]
                        except NotSupportedImageEncodingError:
                            #not supported encoding
                            self.redirect('/error/' + 'The url [' + imgurl + '] is not a supported encoding image')
                            return
                        img = Img(uploader = user,
                                  imgId = imgId,
                                  contentType = resp.headers.get('Content-Type','image/jpeg'),
                                  contentLength = int(resp.headers.get('Content-Length',len(resp.content))),
                                  content = resp.content,
                                  thumbnail = tb,
                                  accessTimes = 0,
                                  originalURL = imgurl
                                  )
                        #we save it to db
                        img.put()
                    self.redirect('/look/'+imgId)
                    return
                else:
                    #not supported encoding
                    self.redirect('/error/' + 'The url [' + imgurl + '] is not a supported encoding image')
                    return
            else:
                #not a image
                self.redirect('/error/' + 'The url [' + imgurl + '] is not a image')
                return
        else:
            #fetch error
            self.redirect('/error/' + 'error occor while fetching url [' + imgurl + ']')
            return
    
class logout(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_logout_url('/'))
        return 


def main():
    application = webapp.WSGIApplication(
                           [('/steal/.*', stealimg),
                           ('/logout', logout)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

